//
//  String.swift
//  vgbox
//
//  Created by Swift Xcode on 2017/5/19.
//  Copyright © 2017年 Swift Xcode. All rights reserved.
//

import Foundation
import Alamofire
import RxCocoa
import RxSwift
import CommonCrypto
import HandyJSON
import CoreLocation

extension String {
    
    var length: Int { return count }
    
    ///获取首字符
    var firstChar: String {
        return String(self[self.startIndex])
    }
    
    ///获取最后一个字符
    var lastChar: String {
        return String(self[self.index(before: self.endIndex)])
    }
    
    ///删除字符串中最后一个字符
    var removeLastChar: String {
        let value = self[..<self.index(before: self.endIndex)]
        return String(value)
    }
    
    /// 移除所有空格
    var removeWhiteSpace: String {
        return self.replacingOccurrences(of: " ", with: "")
    }
    
    /// 获取/插入字符
    ///
    /// - Parameter index: 指定位置
    subscript(index:Int) -> String
    {
        get{
            if (index > self.count - 1 || index < 0)
            {
                return "";
            }
            return String(self[self.index(self.startIndex, offsetBy: index)])
        }
        set{
            let tmp = self
            self = ""
            for (idx, item) in tmp.enumerated() {
                if idx == index {
                    self += "\(newValue)"
                }else{
                    self += "\(item)"
                }
            }
        }
    }
    
    /// 截取字符串
    ///
    /// - Parameters:
    ///   - start: 开始位置
    ///   - end: 结束位置
    subscript(start:Int, end:Int) -> String {
        
        if (start > self.count || start < 0 || start > end)
        {
            return ""
        }
        let s = self.index(self.startIndex, offsetBy: start)
        var e = self.index(self.startIndex, offsetBy: self.count)
        if (end < self.count)
        {
            e = self.index(self.startIndex, offsetBy: end + 1)
        }
        return String(self[s..<e])
    }
    
    /// 截取字符串
    ///
    /// - Parameters:
    ///   - maxIndex: 结束位置
    func subString(to maxIndex: Int) -> String {
        guard maxIndex < self.count && maxIndex > 0  else { return self }
        let toIndex = self.index(self.startIndex, offsetBy: maxIndex)
        return String(self[..<toIndex])
    }
    
    /// 检查文本是否是长空格
    func checkWhiteSpace() -> Bool {
        
        guard count > 0 else { return false }
        let newStr = trimmingCharacters(in: .whitespacesAndNewlines)
        if newStr == "" { return false }
        return true
    }
    
    /// 判断字符串中是否是由字母或者数字组成
    func checkPassword() -> Bool {
        
        let reGex = "^[A-Za-z0-9]+$" // 正则表达式
        let predicate = NSPredicate(format: "SELF MATCHES %@", reGex)
        let result = predicate.evaluate(with: self)
        return result
    }
    
    /// 是否由数字字母组成
    func checkNumANdletter() -> Bool {
        let reGex = "^[A-Za-z0-9]*" // 正则表达式
        let predicate = NSPredicate(format: "SELF MATCHES %@", reGex)
        let result = predicate.evaluate(with: self)
        return result
    }
    
    ///是否全是字母
    
    func checkIsletter() -> Bool{
        let reGex = "^[A-Za-z]*" // 正则表达式
        let predicate = NSPredicate(format: "SELF MATCHES %@", reGex)
        let result = predicate.evaluate(with: self)
        return result
    }
    
    /// 是否是数字
    func checkIsNum() -> Bool {
        let reGex = "[0-9]*"
        let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", reGex)
        return predicate.evaluate(with: self)
    }
    
    /// 是否是金额数字（带小数点，小数点后两位，{0,5}最多6位）
    func checkIsMoneyNum() -> Bool {
        let reGex = "(([0]|(0[.]\\d{0,2}))|([1-9]\\d{0,5}(([.]\\d{0,2})?)))?" // 正则表达式
        let predicate = NSPredicate(format: "SELF MATCHES %@", reGex)
        let result = predicate.evaluate(with: self)
        return result
    }
    
    /// 是否是手机号（1开头的11位数字）
    func checkIsMobileNum() -> Bool {
        let reGex = "^1[0-9]{10}$"
        let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", reGex)
        return predicate.evaluate(with: self)
    }
    
    // 将手机号字符串中间四位变成*号
    func encryptedPhoneNumber() -> String {
        if self.count != 11 { return "" }
        
        var phoneNumber = Array(self)
        _ = phoneNumber.indices.filter{ 3...6 ~= $0 }.map{ phoneNumber[$0] = "*" }
        return String(phoneNumber)
    }
    
    // 将手机号添加分隔符
    func getHyphenText() -> String {
        if self.count != 11 {return "" }
        var result = ""
        for i in 0..<self.count {
            if i == 3 || i == 7{
                result.append("-")
            }
            result.append(self[i])
        }
        return result
    }
    
    /// 获取费用字符串
    ///
    /// - Returns: 计算之后费用字符串
    func getMoneyString() -> String {
        //        let double = Double(self) ?? 0
        //        let string = String(format: "%.2f", double)
        let decimal = Decimal(string: self)
        let string = decimal?.description ?? "0"
        
        return string
    }
    
    /// 获取正式费用字符串
    /**
     *  和getMoneyString()函数的区别
     *  —— getMoneyString()最后两位小数四舍五入
     *  —— getFormalMoneyString()最后两位小数直接截取两位
     */
    /// - Returns: 计算之后费用字符串
    func getFormalMoneyString() -> String {
        // 转换成Double便于计算
        let double = Double(self) ?? 0
        // 先保留3位小数
        let tempSelf = String(format: "%.3f", double)
        // 通过 "." 将字符串分成2部分
        var arr = tempSelf.components(separatedBy: ".")
        /**
         *  截取小数部分前2位,保留三位小数是防止系统方法对小数
         *  四舍五入。这边不需要四舍五入，因为是计算金额，小数部
         *  只能少不能多
         */
        arr[1] = String(arr[1].prefix(2))
        // 将结果通过 "." 拼接之后返回
        return arr.joined(separator: ".")
    }
    
    func isIncludeChinese() -> Bool {
        
        for (_, value) in self.enumerated() {
            if ("\u{4E00}" <= value  && value <= "\u{9FA5}") {
                return true
            }
        }
        return false
    }
    
    /// 判断是否全为中文 0x4E00 0x9FA5 是十六进制数，这是字符编码集中中文字符开始、结束的地方
    func checkIsChinese() -> Bool {
        for (_, value) in self.enumerated() {
            if "\u{4E00}" > value || value > "\u{9FA5}" {
                return false
            }
        }
        return true
    }
    
    /// 隐藏第二个字符
    func hideSecondChar() -> String {
        if self.count >= 2 {
            var str = Array(self)
            _ = str.indices.filter{ 1 ~= $0 }.map{ str[$0] = "*"}
            return String(str)
        }
        return self
    }
    
    ///获取学员。。等几人
    func getStuArr(_ count : Int = 3,_ prefix: String = "",_ suffix : String = "人") -> (String,String){
        var stuName : String = ""
        var otherStr : String = ""
        let stuArr = self.components(separatedBy: ",")
        var array : [String] = []
        if stuArr.count <= count{
            stuName = stuArr.joined(separator: "、")
            otherStr = ""
        }else{
            for i in 0..<count{
                array.append(stuArr[i])
            }
            stuName = array.joined(separator: "、")
            otherStr = "\(prefix)等\(stuArr.count)\(suffix)"
        }
        return (stuName,otherStr)
    }
    
    ///转换成【图】
    func changePicWord() -> String{
        var arr : [String] = []
        arr.removeAll()
        if self.contains(","){
            for (_,_) in self.components(separatedBy: ",").enumerated(){
                arr.append("【图】")
            }
            return arr.joined(separator:"")
        }else{
            return "【图】"
        }
    }
    
    //获取中文的首字母大写
    func findFirstLetterFromString() -> String {
        //转变成可变字符串
        let mutableString = NSMutableString.init(string: self)
        
        //将中文转换成带声调的拼音
        CFStringTransform(mutableString as CFMutableString, nil, kCFStringTransformToLatin, false)
        
        //去掉声调
        let pinyinString = mutableString.folding(options:String.CompareOptions.diacriticInsensitive, locale:   NSLocale.current)
        
        //将拼音首字母换成大写
        let strPinYin = self.polyphoneStringHandle(pinyinString: pinyinString).uppercased()
        
        //截取大写首字母
        let firstString = strPinYin.subString(to: 1)
        
        
        //判断首字母是否为大写
        let regexA = "^[A-Z]$"
        let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
        return predA.evaluate(with: firstString) ? firstString : "#"
    }
    
    //多音字处理，根据需要添自行加
    func polyphoneStringHandle(pinyinString: String) -> String {
        if self.hasPrefix("长") {return "chang"}
        if self.hasPrefix("沈") {return "shen"}
        if self.hasPrefix("厦") {return "xia"}
        if self.hasPrefix("地") {return "di"}
        if self.hasPrefix("重") {return "chong"}
        if self.hasPrefix("单") {return "shan"}
        return pinyinString
    }
    
    
    ///判断是否有表情
    var containsEmoji: Bool {
        for scalar in unicodeScalars {
            switch scalar.value {
            case
            0x00A0...0x00AF,
            0x2030...0x204F,
            0x2120...0x213F,
            0x2190...0x21AF,
            0x2310...0x329F,
            0x1F000...0x1F9CF:
                return true
            default:
                continue
            }
        }
        return false
    }
    
    ///字符串的字符数
    func numberOfChars() -> Int {
        var number = 0
        guard self.count > 0 else {return 0}
        
        for i in 0...self.count - 1 {
            let c: unichar = (self as NSString).character(at: i)
            if (c >= 0x4E00) {
                number += 2
            }else {
                number += 1
            }
        }
        return number
    }
    ///根据字符数，截取字符串
    func subStringWhithChars(count:Int)->String{
        guard self.count > 0 else {
            return ""
        }
        var subCount:Int = 0//self.numberOfChars()
        var str = ""
        for i in 0...self.count - 1 {
            let c: unichar = (self as NSString).character(at: i)
            if  subCount<count{
                if (c >= 0x4E00) {
                    //汉字
                    if count - subCount < 2{//不够一个汉字的位置
                        break
                    }else{
                        str.append((self as NSString).substring(with: NSRange.init(location: i, length: 1)))
                        subCount +=  2
                    }
                }else {
                    //其它
                    str.append((self as NSString).substring(with: NSRange.init(location: i, length: 1)))
                    subCount += 1
                }
            }else{
                break
            }
        }
        return str
    }
    
    ///  根据设置个数判断 数字是否有通过
    /// - Parameter textF: 输入框
    /// - Parameter range: 输入位置
    /// - Parameter importStr: 输入字符
    /// - Parameter prePointCount: 小数点前个数(默认9)
    /// - Parameter behindPointCount: 小数点后个数(默认2)
    func checkTextF(textF: UITextField, changeCharactersInRange range: NSRange, importStr: String, prePointCount: Int = 9, behindPointCount: Int = 2) -> Bool {
        if importStr.isEmpty == true {
            return true
        }
        if textF.text?.contains(".") == true { // 只能输入一个.
            if importStr == "." {
                return false
            }
            if textF.text?.length ?? 0 >= prePointCount + behindPointCount + 1 {
                return false
            }
            // 判断小数点位数
            guard let ran = textF.text?.range(of: ".") else { return false}
            guard let ran1 = textF.text?.changeToNSRange(range: ran) else { return false}
            if range.location > ran1.location {//小数点后边输入
                if (textF.text?.length ?? 0) - ran1.location == behindPointCount + 1 {
                    return false
                }
                if !"05".contains(importStr){//只能输入0和5
                    return false
                }
                return true
            }else {//小数点前边输入
                if (textF.text?.length ?? 0) >= prePointCount + behindPointCount + 1 {
                    return false
                }
                return true
            }
            
        }else {//无小数
            if textF.text?.length ?? 0 >= prePointCount {
                if importStr == "." {
                    return true
                }
                if importStr == "" {
                    return true
                }
                return false
            }
        }
        
        if textF.text == "0" {//0后面只能输入.
            return importStr == "." ?  true : false
        }
        if importStr == " " {
            return false
        }
        
        return true
    }
    
    
    //取超过四位数变成万
    func exchangeDeposit() -> String{
        guard let value = Double(self) else{
            return self
        }
        if value >= 10000{
            return String(format: "%.3f", Double(value)/10000) + "万"
        }else if  value <= 0{
            return "0.00"
        }else{
            return self
        }
    }
    
    
    ///Double去0
    func reduceZero() -> String{
        if self.contains(".0"){
            return String(format: "%d", Int(self.doubleValue))
        }
        return self
    }
    
    // MARK: - 类型转换
    
    var intValue: Int {
        if let value:Int = Int(self)
        {
            return value
        }
        return 0
    }
    
    var floatValue: Float {
        if let value:Float = Float(self)
        {
            return value
        }
        return 0.0
    }
    
    var doubleValue: Double {
        if let value:Double = Double(self)
        {
            return value
        }
        return 0.0
    }
    
    var boolValue: Bool {
        let value:String = self.lowercased()
        return ["true", "yes", "y", "1"].contains(value)
    }
    
    var isEmpty:Bool {
        return self == ""
    }
    
    static func isEmptyOrNil(_ text: String?) -> Bool {
        if text == "" || text == nil {
            return true
        }
        return false
    }
    
    /// 有小数点的string 向下取整
    var moneyStringToInt: Int {
        return Int(self.doubleValue)
    }
    
    var toInt: Int {
        return Int(self) ?? 0
    }
    
    func toInt(_ value: String?) -> Int {
        return Int(value ?? "0") ?? 0
    }
    
    /// 使用正则表达式替换特殊字符
    func pregReplace(pattern: String,
                     with: String,
                     options: NSRegularExpression.Options = []) -> String {
        
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self,
                                              options: [],
                                              range: NSMakeRange(0, self.count),
                                              withTemplate: with)
    }
    
    ///去括号
    func getSpecialStr() -> String{
        let arr = self.components(separatedBy: "、")
        var newArr : [String] = [String]()
        for (_,s) in arr.enumerated(){
            if s != "" && s.firstChar == "(" && s.lastChar == ")"{
                var ns = s;ns.removeFirst();ns.removeLast()
                newArr.append(ns)
            }else{
                newArr.append(s)
            }
        }
        return newArr.joined(separator: "、")
    }
    
    
    ///md5 32位 加密 （小写)
    var md5: String {
        
        let str = cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(lengthOfBytes(using: .utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize(count: digestLen)
        return String(format: hash as String)
    }
    
    // MARK: - JSON解析相关
    /// jsonString转字符串数组
    //    func getStringsWithJSONString(anyClass: Element) -> [String] {
    //
    //        if let cats = JSONDeserializer<SYModel>.
    //        var picdescribe: [String] = []
    //        if json.arrayValue.count == 0 {
    //            return []
    //        }
    //        for value in json.arrayValue {
    //            picdescribe.append(String(describing: value))
    //        }
    //        return picdescribe
    //    }
    
    /// jsonString转dic
    func getDictionaryFromJSONString() -> [AnyHashable : Any] {
        
        let jsonData: Data = self.data(using: .utf8)!
        do {
            let dict = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            guard (dict as? [AnyHashable : Any]) != nil else { return [:] }
            return dict as! [AnyHashable : Any]
        }
        catch(let error) {
            Debug.print(obj: "json转换发生错误：\(error.localizedDescription)")
            return [:]
        }
    }
    
    //从jsonstring中解析key值对应数据
    //    func getStringValueFromJson(_ key : String) -> String{
    //        var stringValue = ""
    //        if let jsonData = self.data(using: .utf8){
    //            let dic = JSON(jsonData)
    //            if let sText = dic[key].string{
    //                stringValue = sText
    //            }
    //        }
    //        return stringValue
    //    }
    
    /// jsonString转Array
    func getArrayFronJSONString() -> [Any] {
        
        let jsonData: Data = self.data(using: .utf8)!
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if array != nil {
            return array as! [Any]
        }
        return []
    }
    
    //    func getArrayFromJSONString() -> [JSON] {
    //
    //        let jsonData: Data = self.data(using: .utf8)!
    //        let array = JSON(jsonData).array
    //        if let array = array{
    //            return array
    //        }
    //        return []
    //    }
    
    /// String转encode
    var getEncodeString: String {
        guard self.count != 0 else { return ""}
        if let u = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
            return u
        }
        return ""
    }
    
    var saveTwo: String {
        
        // 先保留2位小数
        let tempSelf = String(format: "%.2f", self.doubleValue)
        return tempSelf
    }
    
    // MARK: - 文本宽高相关
    /// 计算文本size
    func calculate(font: CGFloat) -> CGSize {
        
        let rect = NSString(string: self).boundingRect(with: CGSize(width: 0, height: font), options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font):UIFont.boldSystemFont(ofSize: font)]), context: nil)
        let realsize:CGSize = CGSize.init(width: ceil(rect.size.width), height: ceil(rect.size.height))
        return realsize
    }
    
    /// j计算文本高度
    func getTextHeight(font:CGFloat,width:CGFloat) ->CGFloat{
        
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height:0), options: .usesFontLeading , attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font):UIFont.systemFont(ofSize: CGFloat(font))]), context: nil)
        return rect.size.height
    }
    
    /// j计算文本宽度
    func getTextWidth(font:CGFloat,height:CGFloat) ->CGFloat{
        
        let rect = NSString(string: self).boundingRect(with: CGSize(width: 0, height:height), options: .usesFontLeading , attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font):UIFont.systemFont(ofSize: CGFloat(font))]), context: nil)
        return rect.size.width
    }
    
    func ga_widthForComment(fontSize: CGFloat, height: CGFloat = 15) -> CGFloat {
        
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): font]), context: nil)
        return ceil(rect.width)
    }
    
    func ga_widthForCommentWithFont(font:UIFont,height: CGFloat = 15) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): font]), context: nil)
        return ceil(rect.width)
    }
    
    func ga_widthForCommentWithFont(font:UIFont,height: CGFloat = 15,maxWidth:CGFloat)-> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): font]), context: nil)
        return ceil(rect.width) > maxWidth ? maxWidth : ceil(rect.width)
    }
    
    func ga_heightForComment(fontSize: CGFloat, width: CGFloat) -> CGFloat {
        
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): font]), context: nil)
        return ceil(rect.height)
    }
    
    func ga_heightForComment(fontSize: CGFloat, width: CGFloat, maxHeight: CGFloat) -> CGFloat {
        
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): font]), context: nil)
        return ceil(rect.height)>maxHeight ? maxHeight : ceil(rect.height)
    }
    
    /// 将一段文本分成两种颜色显示
    func getDiffColorString(oneColor: UIColor, stringOne: String, twoColor: UIColor, stringTwo: String) -> NSMutableAttributedString {
        
        let textString = NSMutableAttributedString.init(string: self)
        if self.contains(stringOne) && self.contains(stringTwo) {
            let range1 = self.range(of: stringOne)
            let range2 = self.range(of: stringTwo)
            let rangeOne = self.changeToNSRange(range: range1!)
            let rangeTwo = self.changeToNSRange(range: range2!)
            textString.addAttribute(NSAttributedString.Key.foregroundColor , value: oneColor, range: rangeOne)
            textString.addAttribute(NSAttributedString.Key.foregroundColor, value: twoColor, range: rangeTwo)
        }
        return textString
    }
    
    /// 获取一段字符串中相同字符位置集
    func hw_exMatchStrRange(_ matchStr: String) -> [NSRange] {
        
        var selfStr = self as NSString
        var withStr = Array(repeating: "X", count: (matchStr as NSString).length).joined(separator: "") //辅助字符串
        if matchStr == withStr { withStr = withStr.lowercased() } //临时处理辅助字符串差错
        var allRange = [NSRange]()
        while selfStr.range(of: matchStr).location != NSNotFound {
            let range = selfStr.range(of: matchStr)
            allRange.append(NSRange(location: range.location,length: range.length))
            selfStr = selfStr.replacingCharacters(in: NSMakeRange(range.location, range.length), with: withStr) as NSString
        }
        return allRange
    }
    
    func changeToNSRange(range: Range<String.Index>) -> NSRange {
        
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange.init(location: utf16.distance(from: utf16.startIndex, to: from!), length: utf16.distance(from: from!, to: to!))
    }
    
    func changeToRange(nsrange: NSRange) -> Range<String.Index>? {
        
        guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsrange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsrange.length, limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self)
            
            else { return nil }
        return from ..< to
    }
    
    func numberOfLinesWithFont(ft: UIFont, placeWidth: CGFloat) -> NSInteger {
        let size: CGSize = sizeOfFont(ft: ft)
        let newlineNum:NSInteger = self.components(separatedBy: "\n").count - 1 + self.components(separatedBy: "\r").count - 1
        let tmpLine:NSInteger = NSInteger(size.width/placeWidth)
        
        return tmpLine + 1 + newlineNum;
        
    }
    
    func sizeOfFont(ft: UIFont) -> CGSize{
        return self.size(withAttributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font) : ft]))
    }
    
    func getGPSDes() -> String {
        let gpsArr = self.components(separatedBy: ",")
        let longitude = Double(gpsArr[0])
        let latitude = Double(gpsArr[1])
        guard longitude != nil && latitude != nil else { return "" }
        // 经度
        var longitudeStr = String(longitude!)
        if longitude! > 0.00 {
            longitudeStr = String(format: "%.1f", longitude!) + "°E"
        } else {
            longitudeStr = String(longitudeStr.prefix(6)) + "°W"
        }
        // 纬度
        var latitudeStr = String(latitude!)
        if latitude! > 0.00 {
            latitudeStr = String(format: "%.2f", latitude!) + "°N"
        } else {
            latitudeStr = String(latitudeStr.prefix(5)) + "°S"
        }
        
        return longitudeStr + "," + latitudeStr
    }
    
    //仅局限于报名、拼团的GPS返回
    func getGPS() -> String {
        let gpsArr = self.components(separatedBy: ",")
        let longitude = Double(gpsArr[1])
        let latitude = Double(gpsArr[0])
        guard longitude != nil && latitude != nil else { return "" }
        // 经度
        var longitudeStr = String(longitude!)
        if longitude! > 0.00 {
            longitudeStr = String(format: "%.1f", longitude!) + "°E"
        } else {
            longitudeStr = String(longitudeStr.prefix(6)) + "°W"
        }
        // 纬度
        var latitudeStr = String(latitude!)
        if latitude! > 0.00 {
            latitudeStr = String(format: "%.2f", latitude!) + "°N"
        } else {
            latitudeStr = String(latitudeStr.prefix(5)) + "°S"
        }
        return longitudeStr + "," + latitudeStr
    }
    
    
    
    /// 两经纬度之间距离
    //    func getDistance(latFir: Double, longFir: Double, latSec: Double, longSec: Double) -> String? {
    //
    //        var distance: CLLocationDistance?
    //        let pointFir: MAMapPoint? = MAMapPointForCoordinate(CLLocationCoordinate2D(latitude: latFir, longitude: longFir))
    //        let pointSec: MAMapPoint? = MAMapPointForCoordinate(CLLocationCoordinate2D(latitude: latSec, longitude: longSec))
    //        if pointFir != nil && pointSec != nil {
    //            distance = MAMetersBetweenMapPoints(pointFir!, pointSec!)
    //        }
    //
    //        if distance == nil {
    //            return nil
    //        } else if Int(distance!) >= 10000000 {
    //            return "(\(Int(distance!/10000000))万km)"
    //        } else if Int(distance!) >= 1000 {
    //            return "(\(Int(distance!/1000))km)"
    //        } else if Int(distance!) < 1000 {
    //            return "(\(Int(distance!))m)"
    //        }
    //        return nil
    //    }
    
    /// 打电话
    func callSomeOne()
    {
        let telprompt = "telprompt:\(self)"
        if let url = URL(string: telprompt) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)//可以写拨打电话的回调
            } else {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }
    
    func toDate(dateFormat: String) -> Date? {
        
        let lastformat = DateFormatter()
        lastformat.dateFormat = dateFormat
        return lastformat.date(from: self)
    }
    
    func getSize(font: UIFont, maxSize: CGSize) -> CGSize {
        return (self as NSString).boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font) : font]), context: nil).size
    }
    
    // 对可选值解包，为空则返回空字符串
    func getSureValue(_ optionalValue: String?) -> String? {
        var v: String = ""
        if let s = optionalValue {
            v = s
        }
        return v
    }
    
    func glt_base64Decoding() -> String {
        let decodeData = NSData.init(base64Encoded: self, options: NSData.Base64DecodingOptions.init(rawValue: 0))
        if decodeData == nil || decodeData?.length == 0 {
            return "";
        }
        let decodeString = NSString(data: decodeData! as Data, encoding: String.Encoding.utf8.rawValue)
        return decodeString! as String
    }
    
    func changeToDate(formatterString: String) -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = formatterString
        dateFormatter.locale = Locale.init(identifier: "zh_CN")
        return dateFormatter.date(from: self)
    }
    
    // MARK: - 跳转系统设置界面
    static func sy_OpenURL(ctr:UIViewController?,title:String?,message:String?) {
        let url = URL(string: UIApplication.openSettingsURLString)
        let alertController = UIAlertController(title: title ?? "访问受限",
                                                message: message ?? "点击“设置”，允许访问权限",
                                                preferredStyle: .alert)
        let cancelAction = UIAlertAction(title:"取消", style: .cancel, handler:nil)
        let settingsAction = UIAlertAction(title:"前往设置", style: .default, handler: {
            (action) -> Void in
            if  UIApplication.shared.canOpenURL(url!) {
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url!, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]),completionHandler: {(success) in})
                } else {
                    UIApplication.shared.openURL(url!)
                }
            }
        })
        alertController.addAction(cancelAction)
        alertController.addAction(settingsAction)
        if let ctr = ctr{
            ctr.vg_present(alertController, animated: true, completion: nil)
        }else{
            UIApplication.shared.keyWindow?.rootViewController?.vg_present(alertController, animated: true, completion: nil)
        }
        
    }
    
    // 获取 bundle version版本号
    static func getLocalAppBundleid() -> String? {
        if let bundleid: String = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String {
            return bundleid
        }
        return nil
    }
    
    static func getLocalAppVersion() -> String? {
        if let version: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            return version
        }
        return nil
    }
    
    static func getAppName() -> String {
        if let appName = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String {
            return appName
        }
        return "蔚来一起学"
    }
    
    func sy_imageURL() -> URL? {
        return URL(string: String(format: "%@%@", IMGIP, self))
    }
    
    func sy_image() -> UIImage? {
        return UIImage(named: self)
    }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
    guard let input = input else { return nil }
    return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
    return input.rawValue
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
    return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
